<?php

namespace App\Http\Controllers\Employee;

use App\Models\Achievements;
use App\Models\User;
use App\Models\UserGroup;
use App\Models\UserRelation;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class IndexController extends Controller
{
    use AuthenticatesUsers;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->middleware(function (Request $req, $next){
            $employeeid = session()->get('employeeid');
            if (!$employeeid || !Auth::check())
            {
                return redirect('employee/login');
            }
            return $next($req);
        })->only(['index', 'export']);
    }

    public function index()
    {
        $this->assign([
            'username'=>'',
            'time_begin'=>'',
            'time_end'=>'',
            'gid'=>'',
            'upuid'=>0,
            'groups'=>UserGroup::userGroups()->orderBy('creditslower')->get()
        ]);

        $user = $this->user;
        $wallet = $this->user()->wallet()->firstOrCreate([]);
        $query = $this->user()->Achievements();

        $queryParams = [];
        $time_begin = $this->request->input('time_begin');
        if ($time_begin)
        {
            $query = $query->where('created_at', '>', strtotime($time_begin));
            $queryParams['time_begin'] = $time_begin;
        }

        $time_end = $this->request->input('time_end');
        if ($time_end)
        {
            $query = $query->where('created_at', '<', strtotime($time_end)+3600*24);
            $queryParams['time_end'] = $time_end;
        }
        $this->assign($queryParams);

        $items = $query->orderByDesc('id')->paginate(20);
        $this->assign([
            'items'=>$items,
            'pagination'=>$items->render()
        ]);

        return $this->view('employee.index', compact('wallet', 'user'));
    }

    public function relations(Request $request)
    {
        $this->assign([
            'username'=>'',
            'time_begin'=>'',
            'time_end'=>'',
            'gid'=>'',
            'upuid'=>0,
            'groups'=>UserGroup::userGroups()->orderBy('creditslower')->get()
        ]);

        $queryParams = [];
        $upuid = $this->request->get('upuid', 0);
        if (!$upuid) $upuid = $this->uid;

        if ($upuid)
        {
            $query = UserRelation::with(['user.group', 'wallet'])->where('upuid', $upuid);
        } else {
            $query = UserRelation::with(['user.group', 'wallet'])->where('uid', $this->uid);
        }

        $username = $this->request->get('username', '');
        if ($username)
        {
            $queryParams['username'] = $username;
            $query = $query->whereHas('user', function ($query) use ($username){
                return $query->where('username', 'LIKE', "%$username%");
            });
        }

        $time_begin = $this->request->get('time_begin', '');
        if ($time_begin)
        {
            $queryParams['time_begin'] = $time_begin;
            $query = $query->where('created_at', '>', strtotime($time_begin));
        }

        $time_end = $this->request->get('time_end', '');
        if ($time_end)
        {
            $queryParams['time_end'] = $time_end;
            $query = $query->where('created_at', '<', strtotime($time_end));
        }

        $gid = $this->request->get('gid', 0);
        if ($gid)
        {
            $queryParams['gid'] = $gid;
            $query = $query->whereHas('user', function ($query) use ($gid){
                return $query->where('gid', $gid);
            });
        }

        $this->assign($queryParams);

        $items = $query->orderByDesc('created_at')->paginate(20);

        //dd(User::find(1041561)->relation->upuser);
        return $this->view('employee.relations', [
            'items'=>$items,
            'pagination'=>$items->appends($queryParams)->render()
        ]);
    }

    public function detail(Request $request)
    {
        $uid = $request->input('uid', 0);
        $achievements = Achievements::where('uid', $uid)->orderByDesc('id')->limit(30)->get();

        return $this->view('employee.detail', compact('achievements'));
    }

    public function export()
    {
        $data = [
            [
                '用户名',
                '个人业绩',
                '个人佣金',
                '会员等级',
                '绑定时间'
            ]
        ];
        $uid = $this->request->get('uid', 0);
        if (!$uid) $uid = $this->uid;
        $query = UserRelation::with(['user.group', 'wallet'])->where('upuid', $uid);

        $username = $this->request->get('username', '');
        if ($username)
        {
            $query = $query->whereHas('user', function ($query) use ($username){
                return $query->where('username', 'LIKE', "%$username%");
            });
        }

        $time_begin = $this->request->get('time_begin', '');
        if ($time_begin)
        {
            $query = $query->where('created_at', '>', strtotime($time_begin));
        }

        $time_end = $this->request->get('time_end', '');
        if ($time_end)
        {
            $query = $query->where('created_at', '<', strtotime($time_end));
        }

        $gid = $this->request->get('gid', 0);
        if ($gid)
        {
            $query = $query->whereHas('user', function ($query) use ($gid){
                return $query->where('gid', $gid);
            });
        }

        $query->orderByDesc('created_at')->paginate(20)
            ->map(function (UserRelation $relation) use (&$data){
                $data[] = [
                    $relation->user->username,
                    $relation->wallet->node_achievement,
                    $relation->Wallet->node_commission,
                    $relation->user->group->title,
                    @date('Y-m-d H:i:s', $relation->created_at)
                ];
            });


        return collect($data)->downloadExcel(
            'relations.xls',
            'Xls',
            false
        );
    }

    public function exportMe(Request $request)
    {
        $data = [
            [
                '用户名',
                '个人业绩',
                '个人佣金',
                '节点业绩',
                '节点佣金',
                '日期'
            ]
        ];

        $query = $this->user()->Achievements();

        $queryParams = [];
        $time_begin = $this->request->input('time_begin');
        if ($time_begin)
        {
            $query = $query->where('created_at', '>', strtotime($time_begin));
            $queryParams['time_begin'] = $time_begin;
        }

        $time_end = $this->request->input('time_end');
        if ($time_end)
        {
            $query = $query->where('created_at', '<', strtotime($time_end)+3600*24);
            $queryParams['time_end'] = $time_end;
        }
        $this->assign($queryParams);

        $items = $query->orderByDesc('id')->paginate(20);
        foreach ($items as $item)
        {
            $data[] = [
                $this->user()->username,
                $item['achievement'],
                $item['commission'],
                $item['node_achievement'],
                $item['node_commission'],
                @date('Y-m-d', $item->created_at)
            ];
        }

        //dd($data);
        return collect($data)->downloadExcel(
            'achievements.xls',
            'Xls',
            false
        );
    }

    public function showLogin(Request $request)
    {
        return $this->view('employee.login');
    }

    public function redirectTo()
    {
        return url('employee');
    }

    public function validateLogin(Request $request)
    {
        $this->validate($request, [
            'account' => 'bail|required|string|account',
            'password' => 'bail|required|string|password'
        ]);
    }

    public function authenticated(Request $request, $user)
    {
        session()->put('employeeid', $user->uid);
    }

    public function attemptLogin(Request $request)
    {
        $account  = $request->input('account');
        $password = $request->input('password');

        $emailLogin = $this->guard()->attempt([
            'email'=>$account,
            'password'=>$password,
        ], false);

        if ($emailLogin) {
            return true;
        }

        $mobileLogin = $this->guard()->attempt([
            'mobile'=>$account,
            'password'=>$password,
        ], false);

        if ($mobileLogin) {
            return true;
        }

        return false;
    }

    public function loggedOut(Request $request)
    {
        session()->forget('employeeid');
        return redirect('employee/login');
    }

    public function username()
    {
        return 'account';
    }
}
